import { Injectable } from '@nestjs/common';
import { EventEmitter } from 'events';



export interface ChatMessage {
  event: string;
  id: string;
  type: string;
  task_id: string;
  message_id: string;
  conversation_id: string;
  answer?: string;
  created_at?: number;
  metadata?: any;
  usage?: any;
  retriever_resources?: any[];
}

export interface FileMessage {
  event: 'message_file';
  id: string;
  type: string;
  belongs_to: string;
  url: string;
  conversation_id: string;
}

export interface TTSMessage {
  event: 'tts_message' | 'tts_message_end';
  task_id: string;
  message_id: string;
  audio: string;
  created_at: number;
}

export interface ErrorMessage {
  event: 'error';
  task_id: string;
  message_id: string;
  status: number;
  code: string;
  message: string;
}

@Injectable()
export class OpenService {
  private messageEmitter: EventEmitter;

  constructor() {
    this.messageEmitter = new EventEmitter();
  }

  async processChat(taskId: string, messageId: string, conversationId: string) {
    return new Promise((resolve, reject) => {
      try {
        let messageCount = 0;
        const sendMessage = (content: string, isEnd = false) => {
          const message = {
            event: isEnd ? 'message_end' : 'message',
            conversation_id: conversationId,
            message_id: messageId,
            created_at: Date.now(),
            task_id: taskId,
            id: messageId,
            type: 'message',
            answer: content,
            from_variable_selector: [Date.now().toString(), 'text']
          };
          this.messageEmitter.emit('message', `data: ${JSON.stringify(message)}\n\n`);
        };

        const messages = [
          '您好！我是您的AI助手。让我来介绍一下我能为您提供的服务：',
          '1. 智能问答：我可以回答您的各类问题，从日常生活到专业领域，我都会尽力提供准确、有见地的回答。',
          '2. 代码编写：我精通多种编程语言，可以帮您编写代码、调试程序、解决技术难题。',
          '3. 数据分析：我可以帮您处理和分析数据，提供数据可视化建议，发现数据中的价值洞察。',
          '4. 创意写作：无论是文案创作、内容策划，还是文档编写，我都可以提供专业的写作协助。',
          '5. 学习辅导：我可以作为您的学习伙伴，帮助您理解复杂概念，提供学习建议和解答疑惑。',
          '6. 决策支持：面对难题时，我可以为您分析利弊，提供多角度的建议，协助您做出明智的决策。',
          '现在，请告诉我您需要什么帮助，我会竭诚为您服务！'
        ];

        const interval = setInterval(() => {
          if (messageCount < messages.length) {
            sendMessage(messages[messageCount]);
            messageCount++;
          } else {
            clearInterval(interval);
            sendMessage('', true); // 发送结束消息
            resolve(true);
          }
        }, 800); // 每800毫秒发送一条消息，模拟打字效果
      } catch (error) {
        const errorMessage: ErrorMessage = {
          event: 'error',
          task_id: taskId,
          message_id: messageId,
          status: 500,
          code: 'INTERNAL_ERROR',
          message: error.message
        };
        this.messageEmitter.emit('message', errorMessage);
        reject(error);
      }
    });
  }

  subscribeToMessages(callback: (message: ChatMessage | FileMessage | TTSMessage | ErrorMessage) => void) {
    this.messageEmitter.on('message', callback);
  }

  unsubscribeFromMessages(callback: (message: ChatMessage | FileMessage | TTSMessage | ErrorMessage) => void) {
    this.messageEmitter.off('message', callback);
  }



}
